<template>
  <div class="advertise">
    <h2>广告投放管理</h2>
    <div class="line-container">
      <div class="box">
        <el-input class="el-input" v-model="searchQuery" placeholder="输入活动区域搜索" @keyup.enter="searchUsers"></el-input>
        <el-button class="el-button" @click="searchUsers">
          <img src="../../assets/img/search.png" alt="">
          筛选
        </el-button>
        <el-button @click="showAddDialog" class="el-button process">
          新增广告
        </el-button>
        <el-button class="el-button remove" @click="deleteSelected" :disabled="selectedUsers.length === 0">
          删除
        </el-button>
      </div>
      <el-table :data="advertise" stripe ref="userTable" @selection-change="handleTableSelectionChange">
        <el-table-column type="selection" ></el-table-column>
        <el-table-column prop="AdvertiseId" label="广告ID"   width="100"></el-table-column>
        <el-table-column prop="AdvertiseName" label="广告名称"  width="100"></el-table-column>
        <el-table-column prop="AdvertiseMain" label="广告内容"  width="180"></el-table-column>
        <el-table-column prop="AdvertisePictureone" label="轮播图1"  width="180">
          <template slot-scope="scope">
            <img :src="scope.row.AdvertisePictureone" style="width: 100%; height: auto;" alt="广告图">
          </template>
        </el-table-column>
        <el-table-column prop="AdvertisePicturetwo" label="轮播图2"  width="180">
          <template slot-scope="scope">
            <img :src="scope.row.AdvertisePicturetwo" style="width: 100%; height: auto;" alt="广告图">
          </template>
        </el-table-column>
        <el-table-column prop="AdvertisePicturethree" label="轮播图3"  width="180">
          <template slot-scope="scope">
            <img :src="scope.row.AdvertisePicturethree" style="width: 100%; height: auto;" alt="广告图">
          </template>
        </el-table-column>
        <el-table-column prop="AdvertiseTime" label="活动开始时间"  width="160">
          <template slot-scope="scope">
            <div>
              {{ formatTime(scope.row.AdvertiseTime) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="活动状态" >
          <template slot-scope="scope">
            <el-switch v-model="scope.row.AdvertiseState" active-color="#13ce66" inactive-color="#ff4949"
              :active-value="true" :inactive-value="false" @change="advertisefix(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" >
          <template slot-scope="scope">
            <p style="color: blue;cursor: pointer;" @click="showDetailDialog(scope.row)">查看详情</p>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
        :page-sizes="[10, 20, 30]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
        :total="totalUsers">
      </el-pagination>
    </div>
    <div class="line-container">
      <h3 style="margin: 20px 0 40px 5px;">广告效果分析</h3>
      <div class="stats-container">
        <div class="stat-item-1">
          <h3>今日展示量</h3>
          <p class="stat-value">{{ feedbackTotal }}</p>
          <p :class="growthRate > 0 ? 'increase' : 'decrease'"><i class="el-icon-arrow-up"></i> 较昨日 {{ growthRate }}%
          </p>
        </div>
        <div class="stat-item-1">
          <h3>今日点击量</h3>
          <p class="stat-value">{{ averageTime }}</p>
          <p :class="reduceTime > 0 ? 'increase' : 'decrease'"><i class="el-icon-arrow-up"></i> 较昨日 {{ reduceTime }}%
          </p>
        </div>
        <div class="stat-item-1">
          <h3>点击率</h3>
          <p class="stat-value">{{ pendingFeedback }}</p>
          <p :class="reduceFeedback > 0 ? 'increase' : 'decrease'"><i class="el-icon-arrow-down"></i> 较昨日 {{
            reduceFeedback
          }}%</p>
        </div>
        <div class="stat-item-1">
          <h3>活跃广告数</h3>
          <p class="stat-value">{{ satisfactionRate }}%</p>
          <p v-if="improvementRate === satisfactionRate" :class="{ 'gray': true }">
            <i class="el-icon-minus"></i> 较昨日持平
          </p>
          <p v-else :class="improvementRate > satisfactionRate ? 'increase' : 'decrease'">
            <i class="el-icon-arrow-up"></i> 较昨日 {{ improvementRate - satisfactionRate }}%
          </p>
        </div>
      </div>
      <div id="chart" style="width: 1200px; height: 400px;"></div>
    </div>
    <!-- 查看详情弹窗 -->
    <el-dialog :visible.sync="detailDialogVisible" title="商品详情" width="700px">
      <el-form :model="detail" ref="editForm" label-width="200px">
        <div class="detail-row">
          <div style="width: 80%;">
            <img :src="detail.AdvertisePictureone" style="border: 1px solid #ccc;width: 238px; height: 150px;" alt="">
            <img :src="detail.AdvertisePicturetwo" style="border: 1px solid #ccc;width: 238px; height: 150px;" alt="">
            <img :src="detail.AdvertisePicturethree" style="border: 1px solid #ccc;width: 238px; height: 150px;" alt="">
          </div>
          <div>
            <div class="detail-item">
              <h3>{{ detail.AdvertiseName }}</h3>
            </div>
            <div style="margin-top: 15px;">
              <div class="detail-item">
                <p class="detail-label">广告ID</p>
                <p>{{ detail.AdvertiseId }}</p>
              </div>
              <div class="detail-item">
                <p class="detail-label">活动开始时间</p>
                <p>{{ formatTime(detail.AdvertiseTime) }}</p>
              </div>
               <div class="detail-item">
                <p class="detail-label">广告内容</p>
                <p>{{ detail.AdvertiseMain }}</p>
              </div>
            </div>
          </div>
        </div>
      </el-form>
      <span style="position: absolute;right: 20px;bottom: 20px;">
        <el-button @click="detailDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="detailDialogVisible = false">确认</el-button>
      </span>
    </el-dialog>

    <!-- 新增活动弹窗 -->
    <el-dialog :visible.sync="addDialogVisible" title="新增广告" width="700px">
      <el-form :model="newAdvertise" ref="addForm" label-width="200px">
        <div class="detail-row">
          <div style="margin-left: 30px;">
            <div style="width: 238px; height: 150px;    position: relative;">
              <img :src="newAdvertise.AdvertisePictureone || 'http://127.0.0.1:3000/picture/1.png'"
                style="border: 1px solid #ccc;width: 238px; height: 150px;" alt="">
              <form class="uploadForm" enctype="multipart/form-data">
                <input type="file" name="image" placeholder="图片" class="img" ref="imageInputOne">
                <button type="button" class="btn" @click="sendImage(1)">完成</button>
              </form>
            </div>
            <div style="width: 238px; height: 150px; margin-top: 50px;    position: relative;">
              <img :src="newAdvertise.AdvertisePicturetwo || 'http://127.0.0.1:3000/picture/1.png'"
                style="border: 1px solid #ccc;width: 238px; height: 150px;" alt="">
              <form class="uploadForm" enctype="multipart/form-data">
                <input type="file" name="image" placeholder="图片" class="img" ref="imageInputTwo">
                <button type="button" class="btn" @click="sendImage(2)">完成</button>
              </form>
            </div>
          </div>
          <div>
            <div style="margin-right: 30px;width: 238px; height: 150px;    position: relative;">
              <img :src="newAdvertise.AdvertisePicturethree || 'http://127.0.0.1:3000/picture/1.png'"
                style="border: 1px solid #ccc;width: 238px; height: 150px;" alt="">
              <form class="uploadForm" enctype="multipart/form-data">
                <input type="file" name="image" placeholder="图片" class="img" ref="imageInputThree">
                <button type="button" class="btn" @click="sendImage(3)">完成</button>
              </form>
            </div>
            <div class="detail-item1" style="margin-top: 40px;">
              <p class="detail-label1">广告名称</p>
              <el-input style="width: 200px;" v-model="newAdvertise.AdvertiseName" placeholder="请输入广告名称"></el-input>
            </div>
                <div class="detail-item1" style="margin-top: 10px;">
              <p class="detail-label1">广告内容</p>
              <el-input style="width: 200px;" v-model="newAdvertise.AdvertiseMain" placeholder="请输入广告内容"></el-input>
            </div>
            <div class="detail-item1" style="margin-top: 10px;">
              <p class="detail-label1">开始时间</p>
              <el-date-picker style="width: 200px;" v-model="newAdvertise.AdvertiseTime" type="datetime"
                placeholder="请选择广告开始时间" value-format="yyyy-MM-dd"></el-date-picker>
            </div>
          </div>
        </div>
      </el-form>
      <span style="position: absolute;right: 20px;bottom: 10px;">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="advertisepost">确认</el-button>
      </span>
    </el-dialog>

    <!-- 删除确认提示框 -->
    <el-dialog :visible.sync="deleteDialogVisible" title="删除广告" width="350px">
      <p>确定要删除（{{ deleteUserNames.join(', ') }}）广告吗？此操作不可恢复</p>
      <span class="dialog-footer" style="margin-top: 20px;display: block;">
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="advertisedel">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Message } from 'element-ui';
import * as echarts from 'echarts';
import AjaxObj from "../../utils/jqAjaxUrl";
import jq from "jquery";
export default {
  data() {
    return {
      advertise: [],
      searchQuery: '',
      currentPage: 1,
      pageSize: 10,
      totalUsers: 0,
      detail: {},
      detailDialogVisible: false,
      addDialogVisible: false,
      remark: '',
      selectedCategory: '',
      selectedSeller: '',
      selectedBrowse: '',
      selectedEnquire: '',
      selectedCollect: '',
      selectedTransaction: '',
      batchStatus: '',
      batchRemark: '',
      selectedUsers: [],
      currentIndex: 0,
      inputVisible: false,
      inputValue: '',
      newAdvertise: {
        AdvertiseId: '',
        AdvertiseName: '',
        AdvertisePictureone: '',
        AdvertisePicturetwo: '',
        AdvertisePicturethree: '',
        advertisecope: '',
        AdvertiseTime: '',
        AdvertiseMain: '',
        AdvertiseState: false,
      },
      deleteDialogVisible: false,
      deleteUserNames: [],
      feedbackTotal: 12458,
      growthRate: 15.8,
      averageTime: 1245,
      reduceTime: 12.3,
      pendingFeedback: 9.8,
      reduceFeedback: -2.1,
      satisfactionRate: 8,
      improvementRate: 8,
    };
  },
  mounted() {
    document.querySelectorAll('.el-input input, .el-input select').forEach(input => {
      input.addEventListener('focus', () => {
        input.style.outline = 'none';
        input.style.borderColor = '#e2e2e2';
      });
    });
    this.totalUsers = this.advertise.length;
    this.initChart();
    this.goodsadvertise();
  },
  methods: {
    sendImage(pictureIndex) {
      let _this = this;
      const validAdvertiseIds = this.advertise
        .filter(a => /^AD\d{5}$/.test(a.AdvertiseId))
        .map(a => parseInt(a.AdvertiseId.slice(2), 10));
      const maxNumber = validAdvertiseIds.length > 0 ?
        Math.max(...validAdvertiseIds) : 0;
      this.newAdvertise.AdvertiseId = `AD${(maxNumber + 1).toString().padStart(5, '0')}`;
      console.log('newAdvertise.AdvertiseId:', _this.newAdvertise.AdvertiseId);
      let inputRef;
      switch (pictureIndex) {
        case 1:
          inputRef = this.$refs.imageInputOne;
          break;
        case 2:
          inputRef = this.$refs.imageInputTwo;
          break;
        case 3:
          inputRef = this.$refs.imageInputThree;
          break;
        default:
          return;
      }
      if (!inputRef || !inputRef.files[0]) {
        Message.error('请选择图片文件');
        return;
      }
      const formData = new FormData();
      formData.append('image', inputRef.files[0]);
      formData.append('AdvertiseId', _this.newAdvertise.AdvertiseId); // 添加 email 参数
      formData.append('pictureIndex', pictureIndex); // 添加图片索引参数
      jq.ajax({
        type: "post",
        url: AjaxObj.url + "/AdvertisePicture",
        data: formData,
        processData: false,                // jQuery不要去处理发送的数据
        contentType: false,                // jQuery不要去设置Content-Type请求头
        success(res) {
          console.log("发送成功" + res);
          console.log('发送成功')
          if (res.status === 200 && res.data && res.data.AdvertisePicture) {
            switch (pictureIndex) {
              case 1:
                _this.newAdvertise.AdvertisePictureone = res.data.AdvertisePicture;
                break;
              case 2:
                _this.newAdvertise.AdvertisePicturetwo = res.data.AdvertisePicture;
                break;
              case 3:
                _this.newAdvertise.AdvertisePicturethree = res.data.AdvertisePicture;
                break;
            }
          }
        },
        error(err) {
          console.log("发送失败" + err);
        }
      });
    },
    formatTime(timeStr) {
      if (!timeStr) return '';
      const date = new Date(timeStr);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    },
    //活动查看
    goodsadvertise() {
      let _this = this;
      jq.ajax({
        type: "get",
        url: "http://127.0.0.1:3000/goodsadvertise",
        data: {
          value: this.add
        },
        success(res) {
          console.log('res', res);
          if (res.data == "") {
            return;
          } else {
            // 处理 AdvertiseState 数据
            _this.advertise = res.data.map(item => {
              return {
                ...item,
                AdvertiseState: item.AdvertiseState === '开启' ? true : false
              };
            });
            console.log('_this.advertise', _this.advertise);
          }
        }
      });
    },
    // 活动删除方法
    advertisedel() {
      let _this = this;
      // 遍历选中的用户，依次删除
      this.selectedUsers.forEach(advertise => {
        // 错误：this.advertise.AdvertiseId（数组无此属性）
        // advertise.AdvertiseId（当前选中的优惠券对象的属性）
        jq.ajax({
          type: 'delete',
          url: `http://127.0.0.1:3000/advertisedel/${advertise.AdvertiseId}`, // 修正此处
          success(res) {
            if (res.status === 200) {
              console.log(`删除优惠卷 ${advertise.AdvertiseName} 成功`);
              // 从 advertise 数组中移除已删除的优惠券（根据 ID 过滤）
              _this.advertise = _this.advertise.filter(item => item.AdvertiseId !== advertise.AdvertiseId);
            } else {
              Message.error(`删除优惠卷 ${advertise.AdvertiseName} 失败`);
              console.log(`删除优惠券失败，响应状态码:`, res.status);
            }
          },
          error(err) {
            console.error(`删除优惠卷 ${advertise.AdvertiseName} 失败:`, err);
            Message.error(`删除优惠卷 ${advertise.AdvertiseName} 失败`);
          }
        });
      });

      // 清空选中状态
      this.selectedUsers = [];
      this.deleteUserNames = [];
      this.deleteDialogVisible = false;
      this.totalUsers = this.advertise.length;
      this.currentPage = 1;
    },
    // 活动状态方法
    advertisefix(row) {
      const AdvertiseState = row.AdvertiseState ? '开启' : '关闭';
      jq.ajax({
        type: 'put',
        url: `http://127.0.0.1:3000/advertisefix`,
        data: {
          AdvertiseId: row.AdvertiseId,
          AdvertiseState: AdvertiseState
        },
        success(res) {
          if (res.status === 200) {
            Message.success(`更新优惠卷${row.AdvertiseName} 成功`);
            console.log('更新优惠券成功');
          } else {
            Message.error('更新失败');
            console.log('更新优惠券失败，响应状态码:', res.status);
          }
        },
        error(err) {
          console.error('更新失败:', err);
          Message.error('更新失败');
          // 恢复原来的状态
          row.AdvertiseState = !row.AdvertiseState;
        }
      });
    },

    // 活动方法
    advertisepost() {
      console.log('进入 advertisepost 方法');
      let _this = this;
      // 过滤掉不符合格式的 AdvertiseId
      const validAdvertiseIds = this.advertise
        .filter(a => /^AD\d{5}$/.test(a.AdvertiseId))
        .map(a => parseInt(a.AdvertiseId.slice(2), 10));
      const maxNumber = validAdvertiseIds.length > 0 ?
        Math.max(...validAdvertiseIds) : 0;
      this.newAdvertise.AdvertiseId = `AD${(maxNumber + 1).toString().padStart(5, '0')}`;

      jq.ajax({
        type: 'post',
        url: 'http://127.0.0.1:3000/advertisepost',
        data: {
          // 使用value-format后直接获取正确格式字符串，无需额外处理
          AdvertiseTime: _this.newAdvertise.AdvertiseTime,
          AdvertiseName: _this.newAdvertise.AdvertiseName,
          AdvertisePictureone: _this.newAdvertise.AdvertisePictureone,
          AdvertisePicturetwo: _this.newAdvertise.AdvertisePicturetwo,
          AdvertisePicturethree: _this.newAdvertise.AdvertisePicturethree,
          AdvertiseId: _this.newAdvertise.AdvertiseId,
          AdvertiseMain: _this.newAdvertise.AdvertiseMain,
          // 将布尔值转换为字符串
          AdvertiseState: _this.newAdvertise.AdvertiseState ? '开启' : '关闭'
        },
        success(res) {
          if (res.status === 200) {
            _this.addDialogVisible = false;
            _this.advertise.push(_this.newAdvertise);
            _this.totalUsers = _this.advertise.length;
            Message.success(`添加活动 ${_this.newAdvertise.AdvertiseName} 成功`);
            _this.goodsadvertise();
          }
        }
      });
    },

    searchUsers() {
      this.currentPage = 1; // 搜索时重置到第一页
      // 不需要手动过滤，计算属性会自动处理
      // 只需要更新总数量
      this.totalUsers = this.advertise.filter(advertise =>
        advertise.AdvertiseName.includes(this.searchQuery)
      ).length;
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      // 切换页大小后重置到第一页
      this.currentPage = 1;
      // 更新总数量
      this.totalUsers = this.advertise.filter(advertise =>
        advertise.AdvertiseName.includes(this.searchQuery)
      ).length;
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
    },
    initChart() {
      const myChart = echarts.init(document.getElementById('chart'));
      const chartOptions = {
        legend: {
          data: ['展示量', '点击量']
        },
        xAxis: {
          type: 'category',
          data: ['11-01', '11-02', '11-03', '11-04', '11-05', '11-06', '11-07']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '展示量',
            type: 'line',
            data: [12000, 13000, 11000, 15000, 12000, 14000, 15000]
          },
          {
            name: '点击量',
            type: 'line',
            data: [500, 500, 500, 700, 600, 700, 800]
          }
        ]
      };
      myChart.setOption(chartOptions);
    },
    showDetailDialog(row) {
      if (!row) {
        console.error('传递的行数据row未定义');
        return;
      }
      this.detail = row;
      this.detailDialogVisible = true;
    },
    showAddDialog() {
      this.newAdvertise = {
        AdvertiseName: '',
        AdvertiseId: '',
        AdvertisePictureone: '',
        AdvertisePicturetwo: '',
        AdvertisePicturethree: '',
        AdvertiseTime: '',
        AdvertiseMain: '',
        AdvertiseState: false
      };
      this.addDialogVisible = true;
    },
    handleTableSelectionChange(selection) {
      this.selectedUsers = selection;
      this.deleteUserNames = selection.map(user => user.AdvertiseName);
    },
    deleteSelected() {
      this.deleteDialogVisible = true;
    },
  },
  created() {
    this.totalUsers = this.advertise.length;
  }
};
</script>

<style lang="less" scoped>
.advertise {
  overflow: hidden;
  padding: 70px 20px 20px 230px;
  background-color: #F9FAFB;
  width: 100%;

  h2 {
    display: block;
    visibility: visible;
    margin-left: 10px;
  }

  .line-container {
    box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3);
    border-radius: 10px;
    border: 1px solid #e9e8e8;
    background-color: white;
    position: relative;
    margin: 20px 10px;
    padding: 20px 40px;
    width: 99%;

    .description-ellipsis {
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .box {
      width: 90%;

      select {
        margin-right: 10px;
      }

      .el-input {
        width: 400px;
        height: 40px;
        padding-left: 20px;
        color: #5d5a5a;
        font-size: 16px;
        margin: 10px 0 15px -12px;

        span {
          padding: 10px;
        }

        input {
          padding: 10px 34px;
          border-radius: 5px;
          border: 1px solid #e2e2e2;
          color: #5d5a5a;
        }
      }

      .el-button {
        margin-left: 10px;
        padding: 12px 25px;
        border-radius: 8px;


        img {
          position: relative;
          top: 2px;
          width: 15px;
          height: 15px;
        }
      }

      .remove {
        background-color: #f11f1f;
        color: white;
        position: absolute;
        top: 14px;
        right: 25px;
      }

      .process {
        background-color: #1f3ff1;
        color: white;
        position: absolute;
        top: 15px;
        right: 120px;
      }

      .border {
        border: 1px solid #e2e2e2;
        border-radius: 5px;
        background-color: transparent;
        font-size: 16px;
        padding-left: 20px;

        img {
          position: relative;
          top: 3px;
          right: 2px;
          width: 16px;
          height: 16px;
        }
      }

      .button {
        width: 400px;
        height: 40px;
        margin: 10px;
        border: transparent;
        background-color: #007BFF;
        color: white;
      }

      .color {
        background-color: #1f3ff1;
        color: white;
      }

    }
  }

  .pop {
    display: inline-block;
    vertical-align: top;
    margin-left: 10px;

    p {
      font-size: 17px;
    }
  }

  .detail-row {
    display: flex;
    justify-content: space-around;
    margin-bottom: 10px;
    width: 100%;

    .btn {
      position: absolute;
      bottom: -30px;
      right: 5px;
    }
  }

  .detail-main {
    width: 90%;
  }

  .detail-item {
    flex: 1;
    margin-right: 10px;
    margin-top: 20px;
  }

  .detail-item1 {
    flex: 1;
    margin-right: 10px;
  }


  .detail-label {
    display: block;
    color: rgb(160, 160, 160);
    margin-bottom: 5px;
    font-weight: normal;

    span {
      color: #5d5a5a;
      margin: 0 10px;
    }
  }

  .detail-label1 {
    width: 100px;
    display: block;
    color: rgb(160, 160, 160);
    margin-bottom: 5px;
    font-weight: normal;

    span {
      color: #5d5a5a;
      margin: 0 10px;
    }
  }

  .close-button {
    background-color: #f4f4f4;
    color: #666;
    border: 1px solid #ccc;
  }

  .send-button {
    background-color: #409eff;
    color: white;
    border: none;
  }

  .confirm-button {
    background-color: #27c24c;
    color: white;
    border: none;
  }

  .stats-container {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    margin: 20px 10px;
  }

  .stat-item-1 {
    width: calc(25% - 50px);
    margin-bottom: 20px;
    border-radius: 10px;
    border: 1px solid #e9e8e8;
    border-radius: 5px;
    padding: 20px;
  }

  .stat-value {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 10px;
  }

  .stat-change {
    color: green;
  }

  .increase {
    color: green;
  }

  .gray {
    color: #7a7a7a;
  }

  .decrease {
    color: red;
  }

  .stat-tip {
    color: rgb(255, 115, 0);
  }
}
</style>